package com.paishen.peiniwan;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.util.SpfsUtil;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.widget.TouchToBackLayout;
import com.umeng.analytics.MobclickAgent;
import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayInputStream;
import java.io.File;

import de.greenrobot.event.EventBus;


public class BaseActivity extends AppCompatActivity {
    private static final String IMAGE_FROM_CONTENT = "content";
    private static final String IMAGE_FROM_FILE = "file";
    private static final int REQUEST_CODE_CAPTURE_PICTURE = 204;
    private static final int REQUEST_CODE_PICK_IMAGE = 205;
    private File fCapturePicture;
    protected boolean cropImageMode = true;
    // public static final int ACTION_QUERY_IMAGE = 12305;
    public static final int CODE_FOR_CAMERA_PERMISSION = 102;
    public static final int CODE_FOR_PHOTO_PERMISSION = 103;
    public static final int CODE_FOR_LOCATION_PERMISSION = 104;

    public String TAG;

    public AlertDialog dlgLoginInfo;
    protected TouchToBackLayout layTouchToBack;
    protected boolean isSupportTouchBack = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();

        EventBus.getDefault().register(this);
        LogUtil.i("EventBus onCreate register " + TAG);

        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseUtil.hideSoftInputFromWindowAlways(this);

        EventBus.getDefault().unregister(this);
        LogUtil.i("EventBus onDestroy unregister " + TAG);

        PnwHttpManager.cancel(TAG);

        ActivityCollector.removeActivity(this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void onEventMainThread(com.paishen.peiniwan.BusEvent event) {
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_HTTP_CACHE:
                    PnwOkCallbackAdapter.Cache c = (PnwOkCallbackAdapter.Cache) event.content;
                    if (TAG.equals(c.tag)) {
                        App.i().getHttpCacheUtil().write(c.key, new ByteArrayInputStream(c.content));
                    }
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CODE_FOR_CAMERA_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(R.string.request_permission_camera)
                            .setPositiveButton(R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                }
            }
        } else if (requestCode == CODE_FOR_PHOTO_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openPhotos();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(R.string.request_permission_photo)
                            .setPositiveButton(R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                }
            }
        } else if (requestCode == CODE_FOR_LOCATION_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                onLocationPermissionOpened();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(com.paishen.libamap.R.string.request_permission_location)
                            .setPositiveButton(com.paishen.libamap.R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(com.paishen.libamap.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                    return;
                }
            }
        }
    }

    public void openCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    CODE_FOR_CAMERA_PERMISSION);
            return;
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fCapturePicture = new File(getExternalCacheDir(), C.sp.PICTURE_NAME + System.currentTimeMillis() + ".jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fCapturePicture));
        startActivityForResult(intent, REQUEST_CODE_CAPTURE_PICTURE);
    }

    public void openPhotos() {
        int hasPhotosPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (hasPhotosPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    CODE_FOR_PHOTO_PERMISSION);
            return;
        }

        if (openPhotosNormal() && openPhotosBrowser() && openPhotosFinally())
            ;
    }

    private void cropImage(Uri data) {
        if (!cropImageMode) {
            LogUtil.d("openCamera crop_image by Ucrop\n" + fCapturePicture.getAbsolutePath());
            EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_PICTURE_QUERY_OUT, fCapturePicture.getAbsolutePath()));
            return;
        }

        UCrop.Options options = new UCrop.Options();
        options.setStatusBarColor(0xFF252C4E);
        options.setToolbarColor(0xFFFFFFFF);
        options.setToolbarTitleTextColor(0xFF05131A);

        fCapturePicture = new File(getExternalCacheDir(), C.sp.PICTURE_NAME + System.currentTimeMillis() + ".jpg");

        UCrop.of(data, Uri.fromFile(fCapturePicture))
                .withAspectRatio(1, 1)
                .withMaxResultSize(500, 500)
                .withOptions(options)
                .start(this);
    }

    private boolean openPhotosNormal() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        try {
            startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
        } catch (android.content.ActivityNotFoundException e) {
            return true;
        }
        return false;
    }

    private boolean openPhotosBrowser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(intent, null);
        try {
            startActivityForResult(wrapperIntent, REQUEST_CODE_PICK_IMAGE);
        } catch (android.content.ActivityNotFoundException e1) {
            return true;
        }
        return false;
    }

    private boolean openPhotosFinally() {
        BaseUtil.showToast(R.string.frame_no_photo_album);
        return false;
    }


    protected void onLocationPermissionOpened() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                if (imageUri != null && IMAGE_FROM_FILE.equals(imageUri.getScheme())) {
                    LogUtil.d("openPhotos pick_image\n" + imageUri.getPath());
                    cropImage(Uri.fromFile(fCapturePicture = new File(imageUri.getPath())));
                } else if (imageUri != null && IMAGE_FROM_CONTENT.equals(imageUri.getScheme())) {
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    LogUtil.d("openPhotos pick_image\n" + picturePath);
                    cropImage(Uri.fromFile(fCapturePicture = new File(picturePath)));
                } else {
                    BaseUtil.showToast(R.string.frame_query_image_fail);
                    LogUtil.e("openPhotos unkown uri\n" + imageUri.getPath());
                }
            }
        } else if (requestCode == REQUEST_CODE_CAPTURE_PICTURE) {
            if (resultCode == RESULT_OK) {
                LogUtil.d("openCamera \n" + fCapturePicture.getAbsolutePath());
                cropImage(Uri.fromFile(fCapturePicture));
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            if (resultCode == RESULT_OK) {
                final Uri resultUri = UCrop.getOutput(data);
                LogUtil.d("openCamera resultUri\n" + resultUri.getPath());
                LogUtil.d("openCamera crop_image\n" + fCapturePicture.getAbsolutePath());
                EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_PICTURE_QUERY_OUT, fCapturePicture.getAbsolutePath()));
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (fCapturePicture != null)
            SpfsUtil.write(C.sp.CAPTURE_PICTURE, fCapturePicture.getAbsolutePath());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        String picturePath = SpfsUtil.readString(C.sp.CAPTURE_PICTURE);
        if (!TextUtils.isEmpty(picturePath)) fCapturePicture = new File(picturePath);
        SpfsUtil.remove(C.sp.CAPTURE_PICTURE);
    }

    public final View makeBackView() {
        return makeBackView(true);
    }

    public final ImageView makeBackView(boolean blackMode) {
        ImageView viewBack = (ImageView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
        viewBack.setImageResource(blackMode ? R.mipmap.common_back : R.mipmap.common_back_white);
        viewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        return viewBack;
    }

    @Override
    public void setContentView(int layoutResID) {
        setContentView(LayoutInflater.from(this).inflate(layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        setContentView(view, null);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        View viewContainer;
        if (isSupportTouchBack) {
            layTouchToBack = new TouchToBackLayout(this);
            layTouchToBack.addView(view);
            viewContainer = layTouchToBack;
        } else {
            viewContainer = view;
        }

        if (params != null) {
            super.setContentView(viewContainer, params);
        } else {
            super.setContentView(viewContainer);
        }
    }


}
